/**
 * @Author:Kindear
 * @Date:2021-09-05
 * @Desc:图书检索记录相关方法
 */
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const LOG = 'cloud-book-log';
const db = cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let action = event.action;
  let openid = event.openid || wxContext.OPENID
  switch(action){
    case 'incOne':{
      let word = event.word;
      /**查询是否存在对应记录 */
      let  selectRes = await db.collection(LOG).where({
        keyWord:word
      }).get();
      /**如果没有 则新增 */
      if(selectRes.data.length == 0){
        return await db.collection(LOG).add({
          data:{
            keyWord:word,
            searchTime:1,
            userLog:[openid]
          }
        })
      }else{
        /**如果存在 则更新 */
        return await db.collection(LOG).where({
          keyWord:word
        }).update({
          data:{
            searchTime:_.inc(1),
            userLog:_.addToSet(openid)
          }
        })
      }
      break
    }
    case 'findTop':{
      /**查询搜索记录前10 */
      return await db.collection(LOG).limit(10).orderBy('searchTime','desc').get();
      break
    }
  }
}